<?php 
class ImageComponent extends Object {

	//var $name = 'Image';
    //var $helpers = array('Html');

	var $cacheDir = 'detail/'; // relative to IMAGES_URL path
	
/**
 * Automatically resizes an image and returns formatted IMG tag
 *
 * @param string $path Path to the image file, relative to the webroot/img/ directory.
 * @param integer $width Image of returned image
 * @param integer $height Height of returned image
 * @param boolean $aspect Maintain aspect ratio (default: true)
 * @param array	$htmlAttributes Array of HTML attributes.
 * @param boolean $return Wheter this method should return a value or output it. This overrides AUTO_OUTPUT.
 * @return mixed	Either string or echos the value, depends on AUTO_OUTPUT and $return.
 * @access public
 */
	function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
		
		$types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
		
		//$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;
		$fullpath = WWW_ROOT.IMAGES_URL;
	
		$url = $fullpath.$path;
		
		if (!($size = getimagesize($url))) 
			return; // image doesn't exist
		
		if($size[0] + $size[1] > 3000)
			return;
			
		if ($aspect) { // adjust to aspect.
			if (($size[1]/$height) > ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
				$width = ceil(($size[0]/$size[1]) * $height);
			else 
				$height = ceil($width / ($size[0]/$size[1]));
		}
		
		
		//$relfile = $this->webroot.$this->themeWeb.IMAGES_URL.$this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
		$cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server
		
		if (file_exists($cachefile)) {
			$csize = getimagesize($cachefile);
			$cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
			if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
				$cached = false;
		} else {
			$cached = false;
		}
		
		if (!$cached) {
			$resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
		} else {
			$resize = false;
		}
		
		if ($resize) {
			/*
			$image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
			//$temp = $this->scaleimg($image, $width, $height);
			if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
				imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
	  		} else {
				$temp = imagecreate ($width, $height);
				imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
			}
			call_user_func("image".$types[$size[2]], $temp, $cachefile);
			imagedestroy ($image);
			imagedestroy ($temp);*/
			$temp = $this->scaleimg($url, $width, $height, $types[$size[2]]);
			call_user_func("image".$types[$size[2]], $temp, $url);
		} 		
		
		//return $this->output(sprintf($this->Html->tags['image'], $relfile, $this->Html->parseHtmlOptions($htmlAttributes, null, '', ' ')), $return);
	}
	
	// Scale an image to the passed width and height
    function scaleimg($url, $maxwidth, $maxheight, $type="jpg") {
		$img = call_user_func("imagecreatefrom".$type, $url);
		//$img = imagecreatefromjpeg($url);
        // Get current size and width
        $width = imagesx($img);
        $height = imagesy($img);

        // Compute scale ratio
        //echo("    scale width = ". $width . ", height " . $height . " to lesser of " . $maxwidth/$width . "," .  $maxheight/$height );
        $scale = min($maxwidth/$width, $maxheight/$height);

         // If the image needs scaling, shrink it
         if ($scale < 1) {
            $new_width = floor($scale*$width);
            $new_height = floor($scale*$height);
         } else {
            $new_width = $width;
            $new_height = $height;
         }

        // Create a new temporary image
        if ($this->gd_version() >= 2) {
            $resized_img = imagecreatetruecolor($new_width, $new_height);
         } else {
            $resized_img = imagecreate($new_width, $new_height);
         }

         // Copy and resize old image into new image
         if ($this->gd_version() >= 2) {
            imagecopyresampled($resized_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
         } else {
            imagecopyresized($resized_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
         }

         return $resized_img;
    }
	// The Harvester uses the PHP GD image processing
    // libraries to copy and resize images.  Not all
    // versions support all functionality so it is
    // sometimes necessary to check version numbers
    // when deciding which functions to invoke.  That
    // turns out to be a bit more difficult than one
    // might expect.  This function does the trick. -- Craig Goss
    function gd_version() {

        static $gd_version_number = null;
        if ($gd_version_number === null) {
            // Use output buffering to get results from phpinfo()
            // without disturbing the page we're in.  Output
            // buffering is "stackable" so we don't even have to
            // worry about previous or encompassing buffering.
            ob_start();
            phpinfo(8);
            $module_info = ob_get_contents();
            ob_end_clean();
            if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
                $module_info,$matches)) {
                $gd_version_number = $matches[1];
            } else {
                $gd_version_number = 0;
            }
        }
        return $gd_version_number;
    }
	
}
?>